<template>
  <div>
    <n-card>
      <n-space style="margin-bottom: 10px">
        <n-input v-model:value="queryForm.title" placeholder="请输入标题" style="width: 300px">
        </n-input>
        <n-button type="primary" @click="loadStoryList">查询</n-button>
      </n-space>
    </n-card>
    <n-card style="margin-top:5px;">
      <n-spin :show="loading">
        <n-space style="margin-bottom: 10px;" justify="start">
          <n-button type="primary" @click="getMediaList();resetStoryForm();modalShow=true;">
            <n-icon style=" display: flex; align-items: center" :size="16">
              <AddCircleOutline></AddCircleOutline>
            </n-icon>新增
          </n-button>
        </n-space>
        <n-scrollbar
            :content-style="{padding: '5px 5px 5px 5px', height: clientHeight - (layoutHeaderHeight  + tabsHeight + 225) + 'px'}">
          <n-grid x-gap="4" y-gap="4" :cols="4" item-responsive responsive="screen">
            <n-gi v-for="story in storyList">
              <n-card closable @close="deleteStory(story)">
                <template #header>
                  <n-ellipsis style="max-width: 250px">
                    {{ story.name }}
                    <template #tooltip>
                      <div style="text-align: center">
                        {{ story.name }}
                      </div>
                    </template>
                  </n-ellipsis>
                </template>
                <n-grid>
                  <n-grid-item :span="14">
                    <n-li><n-tag :type="story.articleType==='2'? 'success':'info' " style="padding: 2px 4px 2px 4px;">{{ story.articleType==='2'?"反推":"原创" }}</n-tag></n-li>
                    <n-li>当前环节 : {{ story.periodName }}</n-li>
                    <n-li>图片进度 : {{ story.successImgNum }} / {{ story.totalNum }}</n-li>
                    {{story.voicePlayType}}
                    <n-li v-if="story.articleType === '1'"  > 音频上传 : {{ ( story.extraAudioFileId === '' || story.extraAudioFileId=== null )? 0:1}} / 1  </n-li>

                    <n-li v-if="story.articleType === '2' && story.voicePlanType ==='uploadVoice'">音频上传 : {{ ( story.extraAudioFileId === '' || story.extraAudioFileId=== null )? 0:1}} / 1 </n-li>
                    <n-li v-if="story.articleType === '2' && story.voicePlanType ==='videoVoice'">视频原声 : 1 / 1</n-li>
                    <n-li v-if="story.articleType === '2' && story.voicePlanType === 'systemVoice'">音频进度 : {{ story.successAudioNum }} / {{ story.totalNum }}</n-li>



                  </n-grid-item>
<!--                  <n-grid-item :span="10" v-if="story?.taskCommonInfoModel?.queueImageTaskNum>0 || story?.taskCommonInfoModel?.queueAudioTaskNum>0 ">-->
<!--                    后台任务 :<n-tag size="small" type="success">启动</n-tag>-->
<!--                    <br>-->
<!--                    图片队列 : <n-tag size="tiny" type="success">{{story?.taskCommonInfoModel?.queueImageTaskNum}}</n-tag>-->
<!--                    <br>-->
<!--                    音频队列 : <n-tag size="tiny" type="warning">{{story?.taskCommonInfoModel?.queueAudioTaskNum}}</n-tag>-->
<!--                  </n-grid-item>-->
                </n-grid>

                <template #action>
                  <n-space justify="space-between">
                    <n-space justify="start">
                      <n-button type="primary" @click="crate(story)">创作</n-button>
                    </n-space>
                    <n-space>
                        <n-button type="info" style="margin-left: 10px" @click="handleSelect(story)">导出草稿</n-button>
                    </n-space>
                  </n-space>
                </template>
              </n-card>
            </n-gi>
          </n-grid>
        </n-scrollbar>
        <n-space justify="end" style="margin-top: 10px">
          <n-pagination
              :display-order="['quick-jumper', 'pages', 'size-picker']"
              :item-count="tableTotal"
              :page-size="paginationReactive.pageSize"
              :page-sizes="paginationReactive.pageSizes"
              show-quick-jumper
              show-size-picker
              :on-update:page-size="onPageSizeChange"
              :on-update:page="onPageChange"
          />
        </n-space>
      </n-spin>
    </n-card>
    <n-drawer v-model:show="drawerShow" :width="drawerWidth" :close-on-esc="false">
      <n-drawer-content title="小说转漫画" :closable="true">
        <novelCreat :story="selectedStory" v-if="createType==='novel'"></novelCreat>
      </n-drawer-content>
    </n-drawer>

    <n-modal
        v-model:show="modalShow"
        :mask-closable="false"
        preset="dialog"
        title="新增作品"
        content="你确认"
        positive-text="确认"
        negative-text="取消"
        @positive-click="addStory"
    >
      <n-form
          ref="storyFormRef"
          :model="storyForm">
        <n-form-item
            label="作品类型"
            path="articleType"
            :rule="{
              trigger: ['blur', 'change'],
              required: true,
              message: '类型'
            }"
        >
          <n-select :options="articleType" v-model:value="storyForm.articleType" default-value="1">

          </n-select>
        </n-form-item>

        <n-form-item label="引用视频" path="mediaId" v-if="storyForm.articleType=='2'">
          <n-select
              v-model:value="storyForm.mediaId"
              :options="getMediaListByType('video')"
              label-field="name"
              value-field="id"
              @update:value="mediaSelect"
              :render-option="mediaInfoSelectRender"
              clearable>
          </n-select>
        </n-form-item>

        <n-form-item label="引用音频" path="mediaId" v-if="storyForm.articleType=='1'">
          <n-select
            v-model:value="storyForm.mediaId"
            :options="getMediaListByType('audio')"
            label-field="name"
            value-field="id"
            @update:value="mediaSelect"
            :render-option="mediaInfoSelectRender"
            clearable>
          </n-select>
        </n-form-item>

        <n-form-item
            label="作品标题"
            path="name"
            :rule="{
              trigger: ['blur', 'change'],
              required: true,
              message: '标题不能为空'
            }"
        >
          <n-input v-model:value="storyForm.name" placeholder="请输入标题"/>
        </n-form-item>

        <n-form-item v-show="false">
          <n-input v-model:value="storyForm.userFileId">
          </n-input>
        </n-form-item>

      </n-form>
    </n-modal>


    <n-modal
        v-model:show="videoCreateShow"
        class="custom-card"
        preset="card"
        style="width: 650px;"
        :mask-closable=false
        title="视频合成设置"
        size="huge"
    >
      <n-form :model="videoCreateForm">
        <n-row>
          <n-col span="12">
            <n-form-item
                label="转场特效"
                path="transition"
                style="width: 90%"
                :rule="{
              trigger: ['blur', 'change'],
              required: true,
              message: '转场特效不能为空'
            }">
              <n-select :options="transition" v-model:value="videoCreateForm.transition">
              </n-select>
            </n-form-item>
          </n-col>
          <n-col span="12">
            <n-form-item
                label="帧数设置"
                path="framesNum"
                style="width: 90%"
                :rule="{
              trigger: ['blur', 'change'],
              required: true,
              message: '帧数设置不能为空'
            }">
              <n-input-number :min="24" :max="60"
                              v-model:value="videoCreateForm.framesNum">

              </n-input-number>
            </n-form-item>
          </n-col>
        </n-row>
        <n-row>
          <n-col span="12">
            <n-form-item
                label="字体大小"
                path="fontSize"
                style="width: 90%"
                :rule="{
              trigger: ['blur', 'change'],
              required: true,
              message: '字体大小不能为空'
            }">
              <n-select :options="fontSize" v-model:value="videoCreateForm.fontSize">

              </n-select>
            </n-form-item>
          </n-col>
          <n-col span="12">
            <n-form-item
                label="字体类型"
                path="fontType"
                style="width: 90%"
                :rule="{
              trigger: ['blur', 'change'],
              required: true,
              message: '字体类型不能为空'
            }">
              <n-select :options="fontType" v-model:value="videoCreateForm.fontType">
              </n-select>
            </n-form-item>
          </n-col>
        </n-row>

      </n-form>
      <template #footer>
        <n-space justify="end">
          <n-button type="primary" @click="submitVideoCreateTask">合成</n-button>
        </n-space>
      </template>
    </n-modal>
    <ExportJianYin  :exportJianYingShow="exportJianYingModalShow" :storyId="selectStoryId" :closeDrawer="closeDrawer"></ExportJianYin>
  </div>
</template>

<script lang="ts" setup>
import {h, onMounted, reactive, ref} from 'vue'
import {storyController} from '@/api/story/story.api'
import {NButton, NTag, NTooltip, useMessage} from 'naive-ui'
import novelCreat from '@/views/pages/create/novel/index.vue'
//@ts-ignore
import Bus from "@/components/file/box/GlobalUploader/utils/bus"
import {videoDict} from '@/dictionary/videoDict'
import {creatorDict} from '@/dictionary/creatorDict'
//@ts-ignore
import fileFunction from "@/libs/globalFunction/file"
import {storeToRefs} from "pinia"
import {useSystemStore} from "@/store/modules/useSystemStore"
import {router} from "@/router"
import {mediaController} from "@/api/controller/media/mediaController"
import {AddCircleOutline,Brush} from '@vicons/ionicons5'
import {taskinfoController} from "@/api/controller/taskinfo/taskinfoController";
import useIntervalAsync from "@/components/common/useIntervalAsync";
import {sysParamController} from "@/api/controller/sysParamController";
import ExportJianYin from "@/views/pages/create/components/exportJianYin.vue";


const {
  clientHeight,
  layoutHeaderHeight,
  collapsed,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());


const {transition, fontSize, fontType} = videoDict()
const {articleType} = creatorDict()
const loading = ref(false)
const message = useMessage()
const storyList = ref<Array<any>>([])
const drawerShow = ref(false)
const drawerWidth = ref(0)
const selectedStory = ref(null)
const createType = ref()
const tableTotal = ref(0)
const exportJianYingModalShow = ref(false)
const selectStoryId = ref()

// 新增modal
const modalShow = ref(false)
// 视频modal
const videoCreateShow = ref(false)
const videoCreateForm = reactive({
  storyId: null,
  transition: '2',
  framesNum: 30,
  fontSize: '2',
  fontType: '2'
})


const storyForm = reactive({
  name: "",
  articleType: "",
  mediaId: "",
  userFileId: ""
})

const resetStoryForm = () => {
  storyForm.name = ""
  storyForm.articleType = ""
  storyForm.mediaId = ""
  storyForm.userFileId = ""
}

const mediaInfoList = ref({})

const queryForm = reactive({
  title: null
})


const paginationReactive = reactive({
  page: 1,
  pageSize: 12,
  pageSizes: [12, 24, 36]
})

const onPageChange = (page: number) => {
  paginationReactive.page = page
  loadStoryList()
}
const onPageSizeChange = (pageSize: number) => {
  paginationReactive.pageSize = pageSize
  loadStoryList()
}

const current = ref(1)

onMounted(() => {
  loadStoryList()
  // 设置当前drawerWidth 宽度
  drawerWidth.value = window.innerWidth;
  window.addEventListener('resize', handleResize);
})


// 窗口宽度变化
const handleResize = () => {
  drawerWidth.value = window.innerWidth;
}


const loadStoryList = () => {
  loading.value = true
  storyController.getStoryList({
    title: queryForm.title
  }, {
    page: paginationReactive.page,
    pageSize: paginationReactive.pageSize
  }).then(res => {
    loading.value = false
    if (res.code === 200) {
      storyList.value = res.data.list
      tableTotal.value = res.data.count
      storyList.value.forEach((item: any) => {
        if(item.taskCommonInfoModel && (item.taskCommonInfoModel.queueImageTaskNum > 0 || item.taskCommonInfoModel.queueAudioTaskNum > 0)){
          getStoryTaskInfo(item)
        }
      })
    } else {
      message.error(res.msg)
    }
  })
}



const getStoryTaskInfo = (storyDto:any) =>{
  const {cancel} = useIntervalAsync(async () => {
    let timeout: any = null;
    await new Promise((resolve) => {
      timeout = setTimeout(() => {
        taskinfoController.getStoryTaskInfo(storyDto.id).then((res) => {
          if(res.code === 200){
            storyDto.taskCommonInfoModel = res.data
            if(res.data.inProgressAudioTaskNum === 0 && res.data.inProgressImageTaskNum === 0){
              cancel()
            }
          }
        })
        resolve('');
      }, 2000);
    });
    return () => {
      clearTimeout(timeout);
    };
  }, 1000 * 2);
}

const getMediaList = () => {
  mediaController.listMediaList({}, {
    page: 1,
    pageSize: 1000
  }).then((res) => {
    if (res.code === 200) {
      mediaInfoList.value = res.data.list
      mediaInfoList.value.forEach((item: any) => {
        item.disabled = true
        if (item.videoToTxtStatus === 'SUCCESS' || item.ocrStatus === 'SUCCESS') {
          item.disabled = false
        }
      })
    }
  })
}

const getMediaListByType = (type:string) =>{
  if (type === 'audio'){
    return mediaInfoList.value.filter((item:any) => item.ext.toLowerCase() === 'mp3' || item.ext.toLowerCase() === 'wav')
  }else {
    return mediaInfoList.value.filter((item:any) => item.ext.toLowerCase() === 'mp4')
  }
}

const mediaInfoSelectRender = (info: any) => {
  return h(NTooltip, null, {
    trigger: () => info.node,
    default: () => {
      console.log(info.node)
      if (info.option.disabled) {
        return h(NTag, {type: 'error'}, () => '请将视频/音频转换为文字')
      } else {
        return h(NTag, {type: 'success'}, () => '类型:' + info.option.ext + '     时长:' + formatSeconds(info.option.videoTime / 1000 / 1000))
      }
    }
  })
}
const crate = (story: any) => {
  let createPage = router.resolve({
    path: '/creator/novel',
    query: {
      storyId: story.id,
      step: story.periodCode
    }
  })
  if (story.articleType == '2') {
    createPage = router.resolve({
      path: '/creator/video',
      query: {
        storyId: story.id,
        step: story.periodCode
      }
    })
  }
  window.open(createPage.href, '_blank')
}

const deleteStory = (story: any) => {
  window.$dialog.error({
    title: "温馨提醒",
    content: "删除操作不可逆，是否继续？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      storyController.deleteStory(story.id).then((res: any) => {
        if (res.code === 200) {
          window.$message.success(res.msg)
          loadStoryList()
        }
      })
    }
  })
}

const addStory = () => {
  if (storyForm.userFileId=== '') {
    window.$message.warning('请选择音频或者视频资源！！！')
    return
  }
  storyController.addStory(storyForm).then((res: any) => {
    if (res.code === 200) {
      window.$message.success(res.msg)
      modalShow.value = false
      loadStoryList()
    }
  })
}

const submitVideoCreateTask = () => {
  storyController.submitVideoCreate(videoCreateForm).then((res: any) => {
    if (res.code === 200) {
      window.$message.success(res.msg)
      videoCreateShow.value = false
    }
  })
}


// 选中资源后
const mediaSelect = (value: string, option: any) => {
  if (storyForm.articleType === '2') {
    storyForm.name = "视频转绘-" + option.name
  } else {
    storyForm.name = "小说转绘-" + option.name
  }

  storyForm.userFileId = option.fileUserId
}


function formatSeconds(seconds) {
  const hour = Math.floor(seconds / 3600);
  seconds = seconds % 3600;
  const minute = Math.floor(seconds / 60);
  seconds = Math.floor(seconds % 60);

  return [
    hour.toString().padStart(2, '0'),
    minute.toString().padStart(2, '0'),
    seconds.toString().padStart(2, '0')
  ].join(':');
}



const handleSelect = (row: any) => {
    selectStoryId.value = row.id
    exportJianYingModalShow.value = true
}


const closeDrawer = () => {
  exportJianYingModalShow.value = false
}
</script>


